
package com.rt.schedulenew.service.impl;

import com.rt.schedulebase.dto.DictExamQueueDto;
import com.rt.schedulebase.entity.DictExamQueue;
import com.rt.schedulebase.entity.ExamSchedule;
import com.rt.schedulebase.mapper.DictExamQueueMapper;
import com.rt.schedulebase.mapper.ExamScheduleMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.util.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import java.util.Map;
import java.util.HashMap;
import com.github.pagehelper.Page;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.global.PageVO;
import com.github.pagehelper.PageHelper;
import com.rt.schedulenew.utils.global.JsonResult;
import java.util.ArrayList;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class DictExamQueueServiceImpl extends ServiceImpl<DictExamQueueMapper, DictExamQueue> implements IDictExamQueueService {
    @Autowired
    private DictExamQueueMapper dictExamQueueMapper;
    @Autowired
    private ICommonService commonServiceImpl;
    @Autowired
    private IDictExamClassService dictExamClassService;
    @Autowired
    private ISourceService sourceService;
    @Autowired
    private IExamSyslogService examSyslogService;

    @Autowired
    private ExamScheduleMapper examScheduleMapper_back;

    @Override
    public List<DictExamQueue> getQueueNameList(DictExamQueue req) {
        QueryWrapper<DictExamQueue> query = new QueryWrapper<>();
        query.eq("QUEUE_TYPE", "0");
        if (StringUtils.isNotBlank(req.getQueueName())) {
            query.eq("QUEUE_NAME", req.getQueueName());
        }
        if (StringUtils.isNotBlank(req.getExamClass())) {
            query.in("EXAM_CLASS", dictExamClassService.getExamClass(req.getExamClass()));
        }
        if (StringUtils.isNotBlank(req.getDeptCode())) {
            query.eq("DEPT_CODE", req.getDeptCode());
        }
        if (StringUtils.isNotBlank(req.getLocation())) {
            query.eq("LOCATION", req.getLocation());
        }
        if (StringUtils.isNotBlank(req.getQueueAlias())) {
            ((query.eq("QUEUE_NAME", req.getQueueAlias())).or()).eq("QUEUE_ALIAS", req.getQueueAlias());
        }
        if (StringUtils.isNotBlank(req.getZoneName())) {
            query.eq("ZONE_NAME", req.getZoneName());
        }
        query.orderByAsc("SORT_NO");
        return dictExamQueueMapper.selectList(query);
    }

    /**
     * 检查队列
     *
     * @param req
     * @return
     */
    @Override
    public List<DictExamQueueDto> deptForQueueNameList(DictExamQueueDto req) {
        // 查询队列字典
        List<DictExamQueueDto> dictQueue = dictExamQueueMapper.getDeptNameForQueue(req);

        List<DictExamQueueDto> queueList = new ArrayList<>();
        if (dictQueue != null && dictQueue.size() > 0) {
            // 将队列的诊室取出来
            List<String> deptNameList = new ArrayList<String>();
            for (DictExamQueueDto examQueue : dictQueue) {
                if (!deptNameList.contains(examQueue.getDeptName())) {
                    deptNameList.add(examQueue.getDeptName());
                }
            }
            // 将检查队列按照 诊室进行分组
            for (String deptName : deptNameList) {
                DictExamQueueDto dto = new DictExamQueueDto();
                // 前端根据 名称和别名分割。取得某一个诊室 下面有哪些检查队列
                // 例: xxx,yyy
                StringBuffer queueNameSb = new StringBuffer();
                StringBuffer queueAliaeSb = new StringBuffer();
                dto.setDeptName(deptName);
                String limitType = commonServiceImpl.getLimitType(req.getExamClass());
                dto.setExamClass(req.getExamClass());
                dto.setLimitType(limitType);

                dictQueue.stream().filter(x -> x.getDeptName().equals(deptName))
                        .forEach(queueDto -> {
                            queueNameSb.append("," + queueDto.getQueueName());
                            String queueAlias = queueDto.getQueueAlias();
                            if (StringUtils.isBlank(queueAlias)) {
                                queueAlias = queueDto.getQueueName();
                            }
                            queueAliaeSb.append("," + queueAlias);
                        });

                dto.setQueueNames(StringUtils.isNotBlank(queueNameSb.toString()) ? queueNameSb.substring(1) : "");
                dto.setQueueAliasStr(StringUtils.isNotBlank(queueAliaeSb.toString()) ? queueAliaeSb.substring(1) : "");
                queueList.add(dto);
            }
        }
        return queueList;
    }

    @Override
    public JsonResult getQueueListPage(DictExamQueueDto dictExamQueueDto) {
        if (dictExamQueueDto.getPageNo() != null && dictExamQueueDto.getPageSize() != null) {
            // 获取检查类别列表
            List<String> examClass = dictExamClassService.getExamClass(dictExamQueueDto.getExamClass());
            dictExamQueueDto.setExamClassList(examClass);
            dictExamQueueDto.setExamClass(null);
            Page<?> page = PageHelper.startPage(dictExamQueueDto.getPageNo(), dictExamQueueDto.getPageSize());
            List<DictExamQueueDto> list = getQueueList(dictExamQueueDto);
            PageVO pageVO = new PageVO();
            pageVO.setPageNo(dictExamQueueDto.getPageNo());
            pageVO.setPageSize(dictExamQueueDto.getPageSize());
            pageVO.setTotal(page.getTotal());
            pageVO.setPages(page.getPages());
            return JsonResultUtil.success("成功", list, pageVO);
        }
        dictExamQueueDto.setExamClassList(CommonUtil.split2List(dictExamQueueDto.getExamClass()));
        dictExamQueueDto.setExamClass(null);

        return JsonResultUtil.success(dictExamQueueMapper.getQueueList(dictExamQueueDto));
    }

    /**
     * 删除预约队列字典表
     *
     * @param dto
     * @return
     */
    @Override
    public JsonResult deleteExamQueue(DictExamQueueDto dto) {
        Map<String, Object> map = new HashMap<>();
        boolean deleteExamQueueResult = false;
        if (dto.getQueueName() != null) {
            QueryWrapper<ExamSchedule> queryWrapper = new QueryWrapper<>();
            Integer count = examScheduleMapper_back.selectCount(queryWrapper);
            if (count > 0) {
                return JsonResultUtil.failure("已有预约数据在该队列下面!");
            }
            // 记录删除日志
            sourceService.examSyslog4DeleteQueue(dto);
            map.put("QUEUE_NAME", dto.getQueueName());
            // 执行删除
            deleteExamQueueResult = removeByMap(map);
        }
        if (deleteExamQueueResult) {
            examSyslogService.saveQueueDesc(ConstantsUtil.ModuleName.DICT_SCHEDULE_QUEUE.name(), ConstantsUtil.OperateName.DELETE.getDesc(), dto, dto);
            return JsonResultUtil.success("删除成功");
        }
        return JsonResultUtil.failure("删除失败");
    }

    @Override
    public JsonResult updateExamQueue(DictExamQueueDto dto) {
        if (StringUtils.isBlank(dto.getQueueName())) {
            return JsonResultUtil.failure("队列名称不能为空");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("QUEUE_NAME", dto.getQueueName());
        QueryWrapper<DictExamQueue> queueQueryWrapper = new QueryWrapper();
        queueQueryWrapper.eq("QUEUE_NAME", dto.getQueueName());
        DictExamQueue oldQueue = dictExamQueueMapper.selectOne(queueQueryWrapper);
        UpdateWrapper<DictExamQueue> updateQueryWrapper = new UpdateWrapper();
        updateQueryWrapper.allEq(map);
        updateQueryWrapper.set(dto.getPriorityOrder() == null, "PRIORITY_ORDER", "");
        updateQueryWrapper.set(dto.getQueueAlias() == null, "QUEUE_ALIAS", "");
        updateQueryWrapper.set(dto.getExpireDays() == null, "EXPIRE_DAYS", "");
        updateQueryWrapper.set(dto.getBeginDays() == null, "BEGIN_DAYS", "");
        updateQueryWrapper.set(dto.getSortNo() == null, "SORT_NO", "");
        updateQueryWrapper.set(StringUtils.isBlank(dto.getLocation()), "LOCATION", "");
        updateQueryWrapper.set(StringUtils.isBlank(dto.getNotice()), "NOTICE", "");
        updateQueryWrapper.set(StringUtils.isBlank(dto.getZoneName()), "ZONE_NAME", "");
        boolean updateExamQueueResult = update(dto, updateQueryWrapper);
        if (updateExamQueueResult) {
            examSyslogService.saveQueueDesc(ConstantsUtil.ModuleName.DICT_SCHEDULE_QUEUE.name(), ConstantsUtil.OperateName.UPDATE.getDesc(), oldQueue, (DictExamQueue) dto);
            return JsonResultUtil.success("修改成功");
        }
        return JsonResultUtil.failure("修改失败");
    }

    @Override
    public JsonResult insertNewExamQueue(DictExamQueueDto dto) {
        if (StringUtils.isBlank(dto.getQueueName()) || StringUtils.isBlank(dto.getQueueAlias()) || StringUtils.isBlank(dto.getExamClass())) {
            return JsonResultUtil.failure("队列名/别名/检查类别/检查科室代码 均不能为空");
        }
        QueryWrapper<DictExamQueue> qw = new QueryWrapper();
        qw.eq("QUEUE_NAME", dto.getQueueName());
        int queueNumWithSameName = count((Wrapper) qw);
        if (queueNumWithSameName != 0) {
            return JsonResultUtil.failure("新增失败:已存在的队列名");
        }
        dto.setQueueType("0");
        dto.setInputCode(PinyinUtil.getPinYinHeadUperChar(dto.getQueueName()));
        boolean insertNewExamQueueResult = save(dto);
        if (insertNewExamQueueResult) {
            examSyslogService.saveQueueDesc(ConstantsUtil.ModuleName.DICT_SCHEDULE_QUEUE.name(), ConstantsUtil.OperateName.INSERT.getDesc(), dto, dto);
            return JsonResultUtil.success("新增成功");
        }
        return JsonResultUtil.failure("新增失败");
    }

    @Override
    public List<DictExamQueue> selectExamQueue(DictExamQueue dto) {
        QueryWrapper<DictExamQueue> query = new QueryWrapper();
        if (StringUtils.isNotBlank(dto.getQueueName())) {
            query.eq("QUEUE_NAME", dto.getQueueName());
        }
        query.orderByAsc("SORT_NO");
        return dictExamQueueMapper.selectList(query);
    }

    @Override
    public List<DictExamQueue> selectList(DictExamQueueDto dto) {
        QueryWrapper<DictExamQueue> qw = new QueryWrapper();
        if (StringUtils.isNotBlank(dto.getQueueName())) {
            qw.eq("QUEUE_NAME", dto.getQueueName());
        }
        if (dto.getExamClassList() != null && dto.getExamClassList().size() > 0) {
            qw.in("EXAM_CLASS", dto.getExamClassList());
        }
        qw.orderByAsc("SORT_NO");
        return dictExamQueueMapper.selectList(qw);
    }

    @Override
    public List<DictExamQueueDto> getQueueList(DictExamQueueDto dto) {
        return dictExamQueueMapper.getQueueList(dto);
    }

    @Override
    public List<String> getLocationList(DictExamQueueDto dto) {
        return dictExamQueueMapper.getLocationList(dto);
    }

    /**
     * 获取队列别名
     *
     * @param req
     * @return
     */
    @Override
    public String getQueueAlias(DictExamQueueDto req) {
        String queueAlias = req.getQueueName();
        List<DictExamQueue> deqList = getQueueNameList(req);
        if (deqList != null && !deqList.isEmpty() && StringUtils.isNotBlank(deqList.get(0).getQueueAlias())) {
            queueAlias = deqList.get(0).getQueueAlias();
        }
        return queueAlias;
    }

    @Override
    public DictExamQueue getInfo(DictExamQueueDto dictExamQueueDto) {
        QueryWrapper<DictExamQueue> query = new QueryWrapper();
        query.eq("QUEUE_NAME", dictExamQueueDto.getQueueName());
        return baseMapper.selectOne(query);
    }
}
